part of 'widget.dart';

class _CardSymbolAssemblageBlockWloc
    extends StatefulWloc<_CardSymbolAssemblageBlockWlocState, CardSymbolAssemblageBlock> {
  late final bloc.CardSymbolAssemblageBlockBloc _bloc;

  late Animation<Color?> textColorAnimation;

  @override
  _CardSymbolAssemblageBlockWlocState get initialState {
    return _CardSymbolAssemblageBlockWlocStateFactory().create(
      blocState: _bloc.state,
    );
  }

  void _onTextChanged() {
    _bloc.requestInputTextChange(
      inputText: widget.textEditingController.text,
    );
  }

  void onLastSymbolDeletionButtonPressed() {
    _bloc.requestLastSymbolDeletion();
  }

  void onHintButtonPressed() {
    widget.onHintButtonPressed();
  }

  VoidCallback? buildSymbolButtonCallback({
    required SymbolInfo symbolInfo,
  }) {
    if (symbolInfo.count == 0) {
      return null;
    }

    return () {
      _bloc.requestSymbolApplying(
        symbol: symbolInfo.symbol,
      );
    };
  }

  void _onBlocStateChanged(
    bloc.CardSymbolAssemblageBlockBlocState blocState,
  ) {
    final updatedState = _CardSymbolAssemblageBlockWlocStateFactory().create(
      blocState: blocState,
    );

    emit(updatedState);

    if (widget.textEditingController.text != blocState.inputText) {
      widget.textEditingController.text = blocState.inputText;
    }
  }

  @override
  void initState() {
    super.initState();

    _bloc = bloc.CardSymbolAssemblageBlockBloc(
      symbolString: widget.symbolString,
      getInitialData: card_symbol_assemblage_block_di.sl(),
      applySymbol: card_symbol_assemblage_block_di.sl(),
      deleteLastSymbol: card_symbol_assemblage_block_di.sl(),
      handleInputTextOuterUpdate: card_symbol_assemblage_block_di.sl(),
    );

    _bloc.stream.listen(_onBlocStateChanged);

    widget.textEditingController.addListener(_onTextChanged);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    final colorTween = ColorTween(
      begin: HomeCoreTheme.of(context).textTheme.cardSymbolInputTextField.color!,
      end: HomeCoreTheme.of(context).cardCorrectAnswerTextColor,
    );

    textColorAnimation = CurvedAnimation(
      parent: widget.textColorAnimationController,
      curve: Curves.easeOutExpo,
    ).drive(colorTween);
  }

  @override
  void dispose() {
    _bloc.close();
    widget.textEditingController.removeListener(_onTextChanged);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _CardSymbolAssemblageBlockView(
      wloc: this,
    );
  }
}
